package com.ran.java_gobang_new.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ran.java_gobang_new.my_exception.MatchException;
import com.ran.java_gobang_new.pojo.request.ChessRequest;
import com.ran.java_gobang_new.pojo.request.MatchRequest;
import com.ran.java_gobang_new.pojo.request.UserInfoRegisterRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.socket.TextMessage;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: ran
 * Date: 2025-09-03
 * Time: 21:50
 */
public class JsonTrans {
    private static final ObjectMapper objectMapper = new ObjectMapper();

    // 将信息转化为 JSON 字符串发送出去
    public static TextMessage trans(Object object) throws JsonProcessingException {
        return new TextMessage(objectMapper.writeValueAsString(object));
    }

    // 将前端传来的信息 message 转化为 匹配对象
    public static MatchRequest trans(TextMessage message) throws JsonProcessingException {
        if (message == null) {
            throw new MatchException("将前端信息 message 转化为 对象, 发生异常");
        }
        return objectMapper.readValue(message.getPayload(), MatchRequest.class);
    }

    // 将前端传来的信息 message 转化为 ChessRequest
    public static ChessRequest transChessRequest(TextMessage message) throws JsonProcessingException {
        if (message == null) {
            throw new MatchException("将前端信息 message 转化为 对象, 发生异常");
        }
        return objectMapper.readValue(message.getPayload(), ChessRequest.class);
    }

}
